package mpo.controller;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import us.codecraft.webmagic.Spider;
import mpo.model.News;
import mpo.serve.MpoSpider;

import com.jfinal.core.Controller;

public class ConfigController extends Controller {

	public void index() {
		render("index.html");
	}

	public void start() throws UnsupportedEncodingException {
		String key = getPara(0);
		System.out.println("start : " + URLDecoder.decode(key, "utf-8"));
		MpoSpider.start(URLDecoder.decode(key, "utf-8"));
		renderText("ok");
	}

	public void stop() throws UnsupportedEncodingException {
		String key = getPara(0);
		System.out.println("stop : " + URLDecoder.decode(key, "utf-8"));
		MpoSpider.stop(URLDecoder.decode(key, "utf-8"));
		renderText("ok");
	}

	public void sites() {
		List<HashMap<String, String>> sites = new ArrayList<HashMap<String, String>>();
		HashMap<String, String> map = new HashMap<String, String>();
		map.put("site", "新浪");
		map.put("url", "http://news.sina.com.cn");
		map.put("status", MpoSpider.getStatus("新浪"));
		map.put("total",
				News.dao.findFirst(
						"select count(1) as total from news where source='新浪'")
						.getLong("total").toString());

		sites.add(map);

		map = new HashMap<String, String>();
		map.put("site", "搜狐");
		map.put("url", "http://news.sohu.com");
		map.put("status", MpoSpider.getStatus("搜狐"));
		map.put("total",
				News.dao.findFirst(
						"select count(1) as total from news where source='搜狐'")
						.getLong("total").toString());

		sites.add(map);

		map = new HashMap<String, String>();
		map.put("site", "腾讯");
		map.put("url", "http://news.tencent.com");
		map.put("status", MpoSpider.getStatus("腾讯"));
		map.put("total",
				News.dao.findFirst(
						"select count(1) as total from news where source='腾讯'")
						.getLong("total").toString());

		sites.add(map);

		map = new HashMap<String, String>();
		map.put("site", "网易");
		map.put("url", "http://news.163.com");
		map.put("status", MpoSpider.getStatus("网易"));
		map.put("total",
				News.dao.findFirst(
						"select count(1) as total from news where source='网易'")
						.getLong("total").toString());

		sites.add(map);
		renderJson(sites);
	}
}
